<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>腾飞健康管理平台</title>
    <link rel="stylesheet" href="lib/layui/css/layui.css">
</head>
<body style="padding: 10px;">
<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
    <legend>项目类型</legend>
</fieldset>
<div id="typeTree"></div>
<script type="text/javascript" src="lib/layui/layui.js"></script>
<script type="text/javascript">
    layui.use(["tree", "jquery", "layer"], function () {
        let tree = layui.tree;
        let $ = layui.jquery;
        let layer = layui.layer;

        let typeTree = null;
        let typeTreeData = getData();

        if (typeTreeData == null || typeTreeData.length <= 0) {
            typeTree = tree.render({
                elem: "#typeTree",
                data: [{
                    title: "无数据",
                }],
                edit: ["update"],
                operate: function (obj) {
                    if (obj.type == "update") {
                        typeTrreeRoot(obj.data);
                        typeTree.reload("typeTreeData", {data: getData()});

                    }
                }
            });
        } else {

            //问题：更新、删除、添加操作后，必须要重新刷新页面才能出现操作结果（typeTree的重载有问题）。
            typeTree = tree.render({
                elem: "#typeTree",
                id: "typeTreeData",
                data: getData(),
                edit: ["update", "add", "del"],
                operate: function (obj) {
                    if (obj.type == "update") {
                        updateNodeName(obj.data);
                        tree.reload('demoId', {data: getData()});
                    } else if (obj.type == "del") {
                        deleteNode(obj.data);
                        tree.reload('demoId', {data: getData()});
                    } else if (obj.type == "add") {
                        addNewNode(obj.data);
                        tree.reload('demoId', {data: getData()});
                    }
                }
            });
        }

        //从数据库中查取树形机构的数据
        function getData() {
            let data = new Array();
            let loadIndex = null;
            $.ajax({
                url: "/getTypeTreeData",
                dataType: "json",
                type: "post",
                async: false,
                beforeSend() {
                    loadIndex = layer.load();
                },
                success(resposneData) {
                    layer.close(loadIndex);
                    data = data.concat(resposneData);
                },
                error() {
                    layer.close(loadIndex);
                    data = null;
                }
            });
            return data;
        }

        //更新节点名称方法
        function updateNodeName(objData) {
            $.ajax({
                url: "/updateNodeName",
                dataType: "json",
                data: JSON.stringify(objData),
                type: "post",
                async: false,
                contentType: "application/json; charset=utf-8",
                success(resposneResult) {
                    console.log(resposneResult.msg);
                    window.location.reload();
                },
                error(XMLHttpRequest, textStatus, errorThrown) {
                    console.log("树形组件节点名称更新失败");
                    console.log(XMLHttpRequest.toString());
                    console.log("textStatus:" + textStatus);
                    console.log("errorThrown:" + errorThrown);
                }

            });
        }

        //添加新节点
        function addNewNode(objData) {
            layer.open({
                title: false,
                type: 2,
                content: ["/addTypeNodePage", "no"],
                btn: ["确定", "关闭"],
                area: ["400px", "140px"],
                btnAlign: 'c',
                closeBtn: false,
                scrollbar: false,
                yes: function (index, layero) {
                    let typeName = $(layero).find("iframe")[0].contentWindow.getTypeName();
                    console.log(typeName);
                    if (typeName == "") {
                        layer.msg("不能提交空值", {time: 1000});
                    } else {
                        let data = "id=" + objData.id + "&typeName=" + typeName;
                        //调用方法，给后台提交数据
                        submitData(data);
                        layer.close(index);
                        window.location.reload();
                    }

                },
                btn2: function (index, layero) {
                    layer.close(index);
                    window.location.reload();
                },
            });
        };

        //给后台提交数据的方法
        function submitData(data) {
            console.log(data);
            $.ajax({
                url: "/addTypeNode",
                data: data,
                dataType: "json",
                type: "get",
                contentType: "application/json; charset=utf-8",
                async: false,
                success: function (responseResult) {
                    if (responseResult.code == 1) {
                        layer.msg(responseResult.msg, {icon: 1, time: 1500});
                    } else {
                        layer.msg(responseResult.msg, {icon: 2, time: 1500})
                    }
                    window.location.reload();
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    console.log("添加新类型请求失败");
                    console.log(XMLHttpRequest.toString());
                    console.log("textStatus:" + textStatus);
                    console.log("errorThrown:" + errorThrown);
                }
            });
        }

        //删除节点方法
        function deleteNode(objData) {
            console.log(objData);
            let typeName = objData.title;
            console.log(objData.children);
            let msg = "";
            if (objData.children == null) {
                msg == "";
            } else if (objData.children != null && objData.children.length > 0) {
                msg = "它的子节点也将被一起删除！";
            }
            layer.confirm("确定要删除节点<span style='color:red'>" + typeName + "</span>吗？" + msg, {icon: 3},
                function (index) {
                    deleteTypes(objData.id);
                    layer.close(index);
                },
                function (index) {
                    layer.close(index);
                });
        }

        //给后台传递被删除节点的信息并执行删除操作
        function deleteTypes(id) {
            $.ajax({
                url: "/deleteItemTypes",
                data: "itemTypeId=" + id,
                dataType: "json",
                type: "get",
                async: false,
                contentType: "application/json; charset=utf-8",
                success: function (responseResult) {
                    if (responseResult.code == 1) {
                        layer.msg(responseResult.msg, {icon: 1, time: 1500});
                    } else {
                        layer.msg(responseResult.msg, {icon: 2, time: 1500})
                    }
                    window.location.reload();
                },
                error: function () {
                    layer.msg("项目类型删除失败", {icon: 2, time: 1500})
                }
            })
        }

        //更新‘项目类型树’的第一个节点根节点
        function typeTrreeRoot(objData){
            console.log(objData);
            $.ajax({
                url: "/addItemTypeTreeRoot",
                data: "itemTypeName="+objData.title,
                dataType: "json",
                type: "get",
                async: true,
                contentType: "application/json; charset=utf-8",
                success: function(responseResult){
                    window.location.reload();
                },
                error: function(){
                    console.log("根节点更新请求失败。")
                }

            })
        }


    });
</script>
</body>
</html>